package callnumber.gtdev5.com.photoVault.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gtdev5.geetolsdk.mylibrary.callback.BaseCallback;
import com.gtdev5.geetolsdk.mylibrary.http.HttpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.SpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import callnumber.gtdev5.com.photoVault.R;
import callnumber.gtdev5.com.photoVault.adapter.TabFragmentPagerAdapter;
import callnumber.gtdev5.com.photoVault.base.BaseActivity;
import callnumber.gtdev5.com.photoVault.bean.EventBusBean;
import callnumber.gtdev5.com.photoVault.bean.GetNewBean;
import callnumber.gtdev5.com.photoVault.constants.AppConstans;
import callnumber.gtdev5.com.photoVault.customview.LazyViewPager;
import callnumber.gtdev5.com.photoVault.fragment.AboutFragment;
import callnumber.gtdev5.com.photoVault.fragment.SettingFragment;
import callnumber.gtdev5.com.photoVault.fragment.VideoFragment;
import callnumber.gtdev5.com.photoVault.fragment.VipFragment;
import callnumber.gtdev5.com.photoVault.utils.MobileInfoUtils;
import callnumber.gtdev5.com.photoVault.widget.DialogDownLoadAPK;
import callnumber.gtdev5.com.photoVault.widget.DialogShowMember;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.frist)
    ImageView frist;
    @BindView(R.id.about)
    ImageView about;

    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.txt_setting)
    TextView txtSetting;
    @BindView(R.id.rv_setting)
    RelativeLayout rvSetting;
    @BindView(R.id.txt_vip)
    TextView txtVip;
    @BindView(R.id.rv_vip)
    RelativeLayout rvVip;
    @BindView(R.id.txt_about)
    TextView txtAbout;
    @BindView(R.id.rv_about)
    RelativeLayout rvAbout;
    @BindView(R.id.myViewpager)
    LazyViewPager myViewpager;
    @BindView(R.id.main_fb)
    FloatingActionButton mainFb;
    @BindView(R.id.video_image)
    ImageView video_image;
    @BindView(R.id.two)
    ImageView two;
    @BindView(R.id.rv_video)
    RelativeLayout rv_video;
    @BindView(R.id.txt_video)
    TextView txt_video;
    private List<Fragment> list;
    private TabFragmentPagerAdapter adapter;
    private SettingFragment settingFragment;
    private long exitTime = 0;

    @Override
    protected int getLayouId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        myViewpager.setCurrentItem(2, false);
        rvSetting.setOnClickListener(this);
        rvVip.setOnClickListener(this);
        rvAbout.setOnClickListener(this);
        mainFb.setOnClickListener(this);
        rv_video.setOnClickListener(this);
        myViewpager.setOnPageChangeListener(new MyPagerChangeListener());
        EventBus.getDefault().register(this);
        checkPermission();
    }
    private void checkPermission() {
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

        }
    }
    @Override
    protected void initDatas() {
        settingFragment = new SettingFragment();
        list = new ArrayList<>();
        list.add(settingFragment);
        list.add(new VideoFragment());
        list.add(new VipFragment());
        list.add(new AboutFragment());
        adapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), list);
        myViewpager.setAdapter(adapter);
        myViewpager.setCurrentItem(0);
        txtSetting.setTextColor(getResources().getColor(R.color.red_main));
        frist.setImageResource(R.mipmap.xiangce_xuanze);
        video_image.setImageResource(R.mipmap.shiping);
        two.setImageResource(R.mipmap.huiyuan);
        about.setImageResource(R.mipmap.wode);
        txtVip.setTextColor(getResources().getColor(R.color.index_color_noSelect));
        txtAbout.setTextColor(getResources().getColor(R.color.index_color_noSelect));

    }

    @Override
    protected void initAction() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rv_setting:
                myViewpager.setCurrentItem(0);
                frist.setImageResource(R.mipmap.xiangce_xuanze);
                video_image.setImageResource(R.mipmap.shiping);
                two.setImageResource(R.mipmap.huiyuan);
                about.setImageResource(R.mipmap.wode);
                txtSetting.setTextColor(getResources().getColor(R.color.red_main));
                txt_video.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                txtVip.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                txtAbout.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                break;
            case R.id.rv_video:
                myViewpager.setCurrentItem(1);

                frist.setImageResource(R.mipmap.xiangce);
                video_image.setImageResource(R.mipmap.shiping_xuanzhong);
                two.setImageResource(R.mipmap.huiyuan);
                about.setImageResource(R.mipmap.wode);

                txtSetting.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                txt_video.setTextColor(getResources().getColor(R.color.red_main));
                txtVip.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                txtAbout.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                break;
            case R.id.rv_vip:
                myViewpager.setCurrentItem(2);
                frist.setImageResource(R.mipmap.xiangce);
                video_image.setImageResource(R.mipmap.shiping);
                two.setImageResource(R.mipmap.huiyuan_xuanzhong);
                about.setImageResource(R.mipmap.wode);
                txtSetting.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                txt_video.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                txtVip.setTextColor(getResources().getColor(R.color.red_main));
                txtAbout.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                break;
            case R.id.rv_about:
                myViewpager.setCurrentItem(3);
                frist.setImageResource(R.mipmap.xiangce);
                video_image.setImageResource(R.mipmap.shiping);
                two.setImageResource(R.mipmap.huiyuan);
                about.setImageResource(R.mipmap.wode_xuanzhong);
                txtSetting.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                txt_video.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                txtVip.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                txtAbout.setTextColor(getResources().getColor(R.color.red_main));
                break;

            default:
                break;
        }
    }

    /**
     * 设置一个ViewPager的侦听事件，当左右滑动ViewPager时菜单栏被选中状态跟着改变
     */
    public class MyPagerChangeListener implements LazyViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
            Log.e("TAG", "onPageScrollStateChanged");
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            Log.e("TAG", "onPageScrolled");
        }

        @Override
        public void onPageSelected(int arg0) {
            switch (arg0) {
                case 0:
                    myViewpager.setCurrentItem(0);
                    frist.setImageResource(R.mipmap.xiangce_xuanze);
                    video_image.setImageResource(R.mipmap.shiping);
                    two.setImageResource(R.mipmap.huiyuan);
                    about.setImageResource(R.mipmap.wode);
                    txtSetting.setTextColor(getResources().getColor(R.color.red_main));
                    txt_video.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    txtVip.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    txtAbout.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    break;
                case 1:
                    myViewpager.setCurrentItem(1);
                    frist.setImageResource(R.mipmap.xiangce);
                    video_image.setImageResource(R.mipmap.shiping_xuanzhong);
                    two.setImageResource(R.mipmap.huiyuan);
                    about.setImageResource(R.mipmap.wode);

                    txtSetting.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    txt_video.setTextColor(getResources().getColor(R.color.red_main));
                    txtVip.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    txtAbout.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    break;
                case 2:
                    myViewpager.setCurrentItem(2);
                    frist.setImageResource(R.mipmap.xiangce);
                    video_image.setImageResource(R.mipmap.shiping);
                    two.setImageResource(R.mipmap.huiyuan_xuanzhong);
                    about.setImageResource(R.mipmap.wode);

                    txtSetting.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    txt_video.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    txtVip.setTextColor(getResources().getColor(R.color.red_main));
                    txtAbout.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    break;
                case 3:
                    myViewpager.setCurrentItem(3);
                    frist.setImageResource(R.mipmap.xiangce);
                    video_image.setImageResource(R.mipmap.shiping);
                    two.setImageResource(R.mipmap.huiyuan);
                    about.setImageResource(R.mipmap.wode_xuanzhong);
                    txtSetting.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    txt_video.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    txtVip.setTextColor(getResources().getColor(R.color.index_color_noSelect));
                    txtAbout.setTextColor(getResources().getColor(R.color.red_main));
                    break;
                default:
                    break;

            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            initDatas();

        }
    }

    //版本更新提醒
    public void checkNews() {
        HttpUtils.getInstance().postNews(new BaseCallback<GetNewBean>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {

            }

            @Override
            public void onSuccess(Response response, GetNewBean o) {
                if (response.isSuccessful() && o != null && o.isHasnew()) {
                    DialogDownLoadAPK loadAPK = new DialogDownLoadAPK(MainActivity.this, "发现新版本，" + o.getVername() + "来啦");
                    loadAPK.show();
                    loadAPK.setOnClickListener(clicked -> {
                        if (clicked) {
                            openActionView(o.getDownurl());
                        } else {
                            if (MobileInfoUtils.getMoblie() && MobileInfoUtils.backTtype(MainActivity.this) != 1) {
                                showBoot();
                            } else {
//                                showNewMemberMind();
                            }
                        }
                    });
                } else {
                    if (MobileInfoUtils.getMoblie() && MobileInfoUtils.backTtype(MainActivity.this) != 1) {
                        showBoot();
                    } else {
//                        showNewMemberMind();
                    }
                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }

    /**
     * 个别手机权限提醒
     */
    private void showBoot() {
//        DialogPermissionBoot dialog = new DialogPermissionBoot(MainActivity.this);
//        dialog.show();
//        dialog.setOnClickListener(i -> {
//            switch (i) {
//                case 0:
//                    showNewMemberMind();
//                    break;
//                case 1:
//                       /* Intent intent = new Intent();
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        try{
//                            intent.setComponent(MobileInfoUtils.jumpStartInterface());
//                        }catch(Exception e){
//                            intent.setAction(Settings.ACTION_SETTINGS);
//                        }*/
//                    Intent intent = MobileInfoUtils.jumpStartInterface(mContext);
//                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    startActivityForResult(intent, 222);
//                    decide();
//                    break;
//                default:
//                    break;
//            }
//        });
    }

    private void decide() {
        PackageManager pm = getPackageManager();
        ComponentName mComponentName = new ComponentName("callnumber.gtdev5.com.fakecall_4.", "callnumber.gtdev5.com.fakecall_4.receiver.BootBroadcastReceiver");
        int i = pm.getComponentEnabledSetting(mComponentName);
        if (i != 1) {
            pm.setComponentEnabledSetting(mComponentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
        }
    }

    /**
     * vip弹窗
     */
    private void showNewMemberMind() {
        int noVipCount = SpUtils.getInstance().getInt(AppConstans.NOVIPUSECOUNT, 0);
        if (vip != null) {
            if (vip.isIsout() && noVipCount >= 1) {
                DialogShowMember dialog = new DialogShowMember(MainActivity.this);
                dialog.show();
                dialog.setOnClickListener((isClicked, id) -> {
                    if (isClicked) {
                        pay(id);
                    } else {

                    }
                });
            }

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000)  //System.currentTimeMillis()无论何时调用，肯定大于2000
            {
                ToastUtils.showShortToast("再按一次退出应用");
                exitTime = System.currentTimeMillis();
            } else {

                finish();
                // System.exit(0);

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void EventBus(EventBusBean message) {
        initDatas();
    }
}
